﻿using System;
using System.Configuration;
using ControleRepresentante.Data.Catalogs;
using ControleRepresentante.Logic.Models;
using FluentNHibernate.Cfg.Db;
using Configuration = NHibernate.Cfg.Configuration;

namespace ControleRepresentante.Logic.Repositories
{
    public interface IRepositoryConfiguration
    {
        UserInfo GetUserInfo();
        Guid? GetRepresentanteId();
    }

    public interface IRepositoryProviderConfiguration : IRepositoryConfiguration
    {
        IPersistenceConfigurer PersistenceConfigurerGenerator(ICatalog catalog);
        void ExposeConfiguration(Configuration configuration);
    }

    public class RepositoryProviderConfiguration : IRepositoryProviderConfiguration
    {
        private readonly Func<UserInfo> m_GetUser;
        private readonly Func<Guid?> m_GetRepresentante;

        public RepositoryProviderConfiguration(Func<UserInfo> getUser, Func<Guid?> getRepresentante)
        {
            m_GetUser = getUser;
            m_GetRepresentante = getRepresentante;
        }

        public UserInfo GetUserInfo()
        {
            return m_GetUser();
        }

        public Guid? GetRepresentanteId()
        {
            return m_GetRepresentante();
        }

        public IPersistenceConfigurer PersistenceConfigurerGenerator(ICatalog catalog)
        {
            switch (ConfigurationManager.ConnectionStrings[catalog.Name].ProviderName)
            {
                case "MySql.Data.MySqlClient":
                    return MySQLConfiguration.Standard
                        .ConnectionString(c => c.FromConnectionStringWithKey(catalog.Name));
                case "System.Data.SqlClient":
                    return MsSqlConfiguration.MsSql2008
                        .ConnectionString(c => c.FromConnectionStringWithKey(catalog.Name));
                default:
                    throw new Exception("Invalid ProviderName");
            }
        }

        public void ExposeConfiguration(Configuration configuration)
        {
#if DEBUG
            configuration.SetInterceptor(new DebugInterceptor());
#endif
        }
    }
}
